package com.part2.action.function;

import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.ajaxanywhere.AAUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.part2.Constants;
import com.part2.action.common.CommonAction;
import com.part2.action.common.Config;
import com.part2.action.common.Encode;
import com.part2.action.common.RandomGUID;
import com.part2.action.common.ToHTML;
import com.part2.action.common.form.CustomActionForm;
import com.part2.action.common.form.ValueObject;
import com.part2.action.common.validator.Validator;
import com.part2.beans.News;
import com.part2.business.function.NewsService;
import com.part2.common.query.Page;

public class NewsAction extends CommonAction<News> {
	private final Log logger = LogFactory.getLog(getClass());
	private NewsService newsService;

	private int start = 0;
	private int page_size = 10;
	private int next_page = 0;
	private int _pre_page = 0;
	private int _now_page = 0;

	public void setNewsService(NewsService newsService) {
		this.newsService = newsService;
	}
	public ActionForward unspecified(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		return null;
	}
	public ActionForward list(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		logger.info("::::::::::News-List");
		String type = request.getParameter("newsType");
		Page<News> p = null;
		Page<News> page = null;
		p = initPage(request, Constants.PRE_PAGE_SIZE);// 设置每页的记录数
		page = newsService.findNews(p, type);
		if (page != null) {
			request.setAttribute("page", page);
		} else {
			request.setAttribute("res", "暂无记录！");
		}
		if (Validator.isNotNull(type))
			request.setAttribute("type", type);
		if (AAUtils.isAjaxRequest(request)) {
			AAUtils.addZonesToRefresh(request, "newsList");
		}
		logger.info("::::::::::News-List End");
		return mapping.findForward("a_news_List");

	}
	
	public ActionForward newsList(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		logger.info("::::::::::News-List");
		String type = request.getParameter("type");
		String newsType = ""+Constants.NEWS_TYPE_NEWS;
		if(Validator.isNotNull(type)){
			if(type.equals("straff"))
				newsType = ""+Constants.NEWS_TYPE_STRAFF;
			if(type.equals("support"))
				newsType = ""+Constants.NEWS_TYPE_SUPPORT;
			if(type.equals("tran"))
				newsType = ""+Constants.NEWS_TYPE_TRAN;
		}
		Page<News> p = null;
		Page<News> page = null;
		p = initPage(request, Constants.PRE_PAGE_SIZE);// 设置每页的记录数
		page = newsService.findNews(p, newsType);
		if (page != null) {
			request.setAttribute("page", page);
		} else {
			request.setAttribute("res", "暂无记录！");
		}
		if (Validator.isNotNull(type))
			request.setAttribute("type", type);
		if (AAUtils.isAjaxRequest(request)) {
			AAUtils.addZonesToRefresh(request, "newsList");
		}
		logger.info("::::::::::News-List End");
		switch (Integer.parseInt(newsType)) {
		case 0:
			return mapping.findForward("newsList");
		case 1:
			return mapping.findForward("straffList");
		case 2:
			return mapping.findForward("tranList");
		case 3:
			return mapping.findForward("supportList");
		default:
			return null;
		}

	}

	public ActionForward search(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		logger.info("::::::::::News-Search");
		ValueObject search = ((CustomActionForm) form).getVoa().getValue(
				"Search");
		String s = search.getField("key");
		if (Validator.isNull(s))
			s = request.getParameter("key");
		Page<News> p = initPage(request, Constants.PRE_PAGE_SIZE);
		Page<News> page = newsService.findNewsBySearch(p, s);
		if (page != null) {
			request.setAttribute("page", page);
			request.setAttribute("key", s);
		} else {
			if (Validator.isNotNull(s))
				request.setAttribute("res", "暂无关于" + s + "的记录！");
			else
				request.setAttribute("res", "请输入关键字！");
		}
		if (AAUtils.isAjaxRequest(request)) {
			AAUtils.addZonesToRefresh(request, "newsList");
		}
		logger.info("::::::::::News-Search End");
		return mapping.findForward("newsList");
	}

	public ActionForward preAdd(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		return mapping.findForward("newsAdd");
	}

	public ActionForward add(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		logger.info("::::::::::News-Add");
		ValueObject nVo = ((CustomActionForm) form).getVoa().getValue("news");
		String type = nVo.getField("type");
		String newsId = "";
		String title = nVo.getField("title");
		String titleEn = nVo.getField("titleEn");
		String content = nVo.getField("content");
		String contentEn = nVo.getField("contentEn");
		String filePath = request.getSession().getServletContext().getRealPath(
				"/")
				+ Constants.NEWS_HTML_PATH;
		String url = Constants.NEWS_URL;
		if (Validator.isNotNull(title)) {
			News news = new News();
			newsId = new RandomGUID() + "-news";
			news.setNewsId(newsId);
			news.setNewsTitle(title);
			news.setNewsTitleEn(titleEn);
			news.setNewsContent(content);
			news.setNewsContentEn(contentEn);
			news.setNewsType(Short.parseShort(type));
			news.setViewNum(0);
			news.setCreateDate(new Date());
			news.setLastModifielDate(new Date());
			newsService.addNews(news);
//			ToHTML.makeHTML(filePath, newsId, url + newsId, null);
		}
		logger.info("::::::::::News-Add End");
		return this.list(mapping, form, request, response);
	}

	public ActionForward preEdit(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		ValueObject nVo = ((CustomActionForm) form).getVoa().getValue("news");
		String newsId = request.getParameter("id");
		if (Validator.isNotNull(newsId)) {
			News news = newsService.findNewsByPrimeKey(newsId);
			if (news != null) {
				nVo.setField("newsId", newsId);
				nVo.setField("title", news.getNewsTitle());
				nVo.setField("titleEn", news.getNewsTitleEn());
				nVo.setField("content", news.getNewsContent());
				nVo.setField("contentEn", news.getNewsContentEn());
				nVo.setField("type", news.getNewsType().toString());
				return mapping.findForward("newsEdit");
			}
		}
		return null;
	}

	public ActionForward edit(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		logger.info("::::::::::News-Eidt");
		ValueObject nVo = ((CustomActionForm) form).getVoa().getValue("news");
		String newsId = nVo.getField("newsId");
		String type = nVo.getField("type");
		String title = nVo.getField("title");
		String titleEn = nVo.getField("titleEn");
		String content = nVo.getField("content");
		String contentEn = nVo.getField("contentEn");
		String root = request.getSession().getServletContext().getRealPath("/");
		String filePath = root + Constants.NEWS_HTML_PATH;
		String url = Constants.NEWS_URL;
		if (Validator.isNotNull(newsId) && Validator.isNotNull(title)) {
			News news = newsService.findNewsByPrimeKey(newsId);
			if (news != null) {
				if (!type.equals(news.getNewsType().toString())) {
					news.setNewsType(Short.parseShort(type));
				}
				news.setNewsTitle(title);
				news.setNewsTitleEn(titleEn);
				news.setNewsContent(content);
				news.setNewsContentEn(contentEn);
				news.setLastModifielDate(new Date());
				newsService.updateNews(news);
//				ToHTML.makeHTML(filePath, newsId, url + newsId, null);
			}
		}
		logger.info("::::::::::News-Eidt End");
		return this.list(mapping, form, request, response);
	}

	/***************
	 * The New Type 
	 * String NEWS_TYPE_NEWS 0 
	 * String NEWS_TYPE_STRAFF 1 
	 * String NEWS_TYPE_TRAN 2 
	 * String NEWS_TYPE_SUPPORT 3
	 */
	public ActionForward show(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		ValueObject nVo = ((CustomActionForm) form).getVoa().getValue("news");
		String id = request.getParameter("nId");
		String get_type = request.getParameter("newsType");
		Short n_type = Short.parseShort(Constants.NEWS_TYPE_NEWS);
		if (Validator.isNotNull(get_type) && Validator.isNumber(get_type)) {
			n_type = Short.parseShort(get_type);
		}
		String title = "";
		String content = "";
		Short type = 0;
		List<News> newsList = null;
		if (Validator.isNotNull(id)) {
			News n = newsService.findNewsByPrimeKey(id);
			if (n != null) {
				title = n.getNewsTitle();
				content = n.getNewsContent();
				type = n.getNewsType();
				nVo.setField("title", title);
				nVo.setField("content", content);
				nVo.setField("type", type + "");
				return mapping.findForward("show");
			}
//		} else {
//			if (Validator.isNotNull(request.getParameter("start")))
//				start = Integer.parseInt(request.getParameter("start"));
//			newsList = newsService.findNewsByType(n_type);
//			if (newsList != null && newsList.size() > 0) {
//				request.setAttribute("newsList", newsList);
//				request.setAttribute("start", new Integer(start));
//				request.setAttribute("page", new Integer(page_size));
//				int previous = start - page_size;
//				if (previous >= 0) {
//					request.setAttribute("preHtml", "list_" + _pre_page
//							+ ".html");
//					request.setAttribute("previous", new Integer(previous));
//				}
//				// if there is a next page, set the next variable
//				int next = start + page_size;
//				if (next < newsList.size()) {
//					request.setAttribute("nextHtml", "list_" + next_page
//							+ ".html");
//					request.setAttribute("next", new Integer(next));
//				}
//				switch (n_type) {
//				case 0:
//					return mapping.findForward("newsList");
//				case 1:
//					return mapping.findForward("straffList");
//				case 2:
//					return mapping.findForward("tranList");
//				case 3:
//					return mapping.findForward("supportList");
//				default:
//					return null;
//				}
//			}
		}
		return null;
	}

	public ActionForward delete(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		logger.info("::::::::::News-Delete");
		String newsId = request.getParameter("newsId");
		if (Validator.isNotNull(newsId)) {
			newsService.deleteNews(newsId);
		}
		logger.info("::::::::::News-Delete End");
		return list(mapping, form, request, response);
	}

	public ActionForward makeHtmlList(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		List newsList = newsService.findNews();
		Iterator it = newsList.iterator();
		String id = "";
		String root = request.getSession().getServletContext().getRealPath("/");
		String webPath = request.getContextPath();
		String filePath = root + Constants.NEWS_HTML_PATH;
		String url = Config.readValue("webSite")+Constants.NEWS_URL;
		String href_url = "";
		boolean listFlag = false;// 判断是否需要生成列表
		if (newsList != null && newsList.size() > 0) {
			response.setContentType("text/html;charset=UTF-8");
			response.getWriter().write("新闻内页开始<br>");
			while (it.hasNext()) {
				logger.info("has next...");
				News n = (News) it.next();
				id = n.getNewsId();
				ToHTML.makeHTML(filePath, id, url + id, null);
				listFlag = true;// 完成所有页面的生成后开始生成列表
				href_url = webPath + Constants.NEWS_HTML_PATH
						+ Encode.encodeByMD5(id) + ".html";
				response.getWriter().write(
						"<a href='" + href_url + "' target='_blank'>"
								+ n.getNewsTitle() + "</a>" + "已生成!<br>");
				logger.info(":::::::::::::::make HTML finsh!:::::::::::::");
			}
			if (listFlag) {
				response.getWriter().write("新闻列表开始<br>");
				int count = newsList.size() / page_size;
				url = Config.readValue("webSite")+Constants.NEWS_LIST_URL;
				if (newsList.size() % page_size > 0)
					count++;
				for (int i = 1; i <= count; i++) {
					_now_page = i;
					_pre_page = _now_page;
					next_page = _now_page;
					if (i == 1)
						next_page = _now_page;
					if (i > 1)
						--_pre_page;
					if (i > 0 && i != count)
						++next_page;
					// 参数i用来保证每一页都是唯一的
					ToHTML.makeHTML(filePath, "list_" + i, url + start + "&i="
							+ new RandomGUID(), "list");
					// 全局变量start
					start += page_size;
					href_url = webPath + Constants.NEWS_HTML_PATH + "list_" + i
							+ ".html";
					response.getWriter().write(
							"<a href='" + href_url + "' target='_blank'>list_"
									+ i + "</a>" + "已生成!<br>");
					logger
							.info(":::::::::::::::make HTML List finsh!:::::::::::::");
				}
				listFlag = false;// 将列表状态恢复为false
			}
			if (!listFlag) {// 回收一些资源
				start = 0;// 完成列表后必须归零
				_now_page = 0;
				_pre_page = 0;
				next_page = 0;
				href_url = null;
			}
		}
		return null;
	}

}
